package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.LogDO;
import com.bootdo.common.service.FileService;
import com.bootdo.common.service.LogService;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.TMagazineDO;
import com.bootdo.system.domain.TMagazinePicturesDO;
import com.bootdo.system.domain.TUserDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.TMagazinePicturesService;
import com.bootdo.system.service.TMagazineService;
import com.bootdo.system.service.TUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 杂志表
 * 
 * @author Ace Lee
 * @email las1990@126.com
 * @date 2019-11-16 21:46:23
 */
 
@Controller
@RequestMapping("/system/tMagazine")
public class TMagazineController extends BaseController {
	private String prefix="system/tMagazine"  ;
	@Autowired
	private TMagazineService tMagazineService;
    @Autowired
    private TMagazinePicturesService tMagazinePicturesService;
    @Autowired
    private BootdoConfig bootdoConfig;
    @Autowired
    private FileService sysFileService;
	@Autowired
	private TUserService tUserService;
	@Autowired
	LogService logService;
	
	@GetMapping()
	@RequiresPermissions("system:tMagazine:tMagazine")
	String TMagazine(){
	    return "system/tMagazine/tMagazine";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("system:tMagazine:tMagazine")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<TMagazineDO> tMagazineList = tMagazineService.list(query);
		int total = tMagazineService.count(query);
		PageUtils pageUtils = new PageUtils(tMagazineList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("system:tMagazine:add")
	String add(){
	    return "system/tMagazine/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("system:tMagazine:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		TMagazineDO tMagazine = tMagazineService.get(id);
		model.addAttribute("tMagazine", tMagazine);
	    return "system/tMagazine/edit";
	}

    @RequestMapping("/unique")
    @ResponseBody
    @RequiresPermissions("system:tMagazine:add")
    public Boolean unique(HttpServletRequest request, TMagazineDO tMagazine) {
        Boolean isExistence = false;
        try {
            if(!StringUtils.isEmpty(tMagazine.getIssn())){
                isExistence = tMagazineService.isExistence(tMagazine);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isExistence;
    }

	/**
	 * 保存
	 */
	@Log("保存杂志")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("system:tMagazine:add")
	public R save( TMagazineDO tMagazine){
		tMagazine.setCreatedUser(getUsername());
		int save = tMagazineService.save(tMagazine);
		if(save>0){
			return R.ok();
		}else if (save==-1){
			return R.error("期刊号已存在");
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@Log("修改杂志")
	@RequiresPermissions("system:tMagazine:edit")
	public R update( TMagazineDO tMagazine){
		tMagazine.setStatus("1");
		tMagazine.setUpdatedUser(getUsername());
		tMagazineService.update(tMagazine);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@Log("删除杂志")
	@RequiresPermissions("system:tMagazine:remove")
	public R remove( Integer id){
		if(tMagazineService.remove(id)>0){
			int del = tMagazinePicturesService.removeByMagazineId(id);
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@Log("批量删除杂志")
	@RequiresPermissions("system:tMagazine:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		tMagazineService.batchRemove(ids);
		if (ids.length>0){
			for (Integer id : ids) {
				int del = tMagazinePicturesService.removeByMagazineId(id);
			}
		}
		return R.ok();
	}


	@RequiresPermissions("system:tMagazine:verify")
	@Log("请求审核页面")
	@GetMapping("/verify/{id}")
	String verify(@PathVariable("id") Integer id, Model model) {
		TMagazineDO magazineDO = tMagazineService.get(id);
		model.addAttribute("tMagazine", magazineDO);

		Map<String, Object> map = new HashMap<>();
		map.put("isValid","1");
		List<TUserDO> userDOS = tUserService.list(map);
		model.addAttribute("verifyUsers", userDOS);
		return prefix + "/verify";
	}


	@RequiresPermissions("system:tMagazine:verify")
//	@Log("审核杂志")
	@PostMapping("/setVerify")
	@ResponseBody
	R verify(TMagazineDO magazineDO) {
		try{
			magazineDO.setVerifyResult(true);
			magazineDO.setStatus("2");
			if(tMagazineService.verify(magazineDO)>0){
				//保存日志
				LogDO logDO = new LogDO();
				logDO.setGmtCreate(new Date());
				logDO.setOperation(magazineDO.getVerifyUser()+"审核杂志 成功，审核信息为："+magazineDO.getVerifyDesc() );
				logDO.setMethod("com.bootdo.system.controller.TMagazineController.verify()");
				logDO.setParams(magazineDO.getVerifyUser());
				UserDO current = ShiroUtils.getUser();
				if(null!=current){
					logDO.setUserId(current.getUserId());
					logDO.setUsername(current.getUsername());
				}
				logService.save(logDO);
			}
			return R.ok();
		}catch (Exception e){
			return R.error(1,e.getMessage());
		}

	}

	@RequiresPermissions("system:tMagazine:verify")
//	@Log("上下架")
	@PostMapping("/setOnOff")
	@ResponseBody
	R setOnOff(TMagazineDO magazineDO) {
		try{
			UserDO current = ShiroUtils.getUser();
			String oper = null;
			if (magazineDO!=null && magazineDO.getStatus().equalsIgnoreCase("3")){
				magazineDO.setIsValid(true);
				oper = "杂志上架 成功";
			}else {
				oper = "杂志下架 成功";
				magazineDO.setIsValid(false);
			}
			magazineDO.setUpdatedUser(getUsername());
			magazineDO.setUpdatedTime(new Date());
			if(tMagazineService.update(magazineDO)>0){
				//保存日志
				LogDO logDO = new LogDO();
				logDO.setGmtCreate(new Date());
				logDO.setOperation(oper);
				logDO.setMethod("com.bootdo.system.controller.TMagazineController.setOnOff()");
				logDO.setParams(magazineDO.getStatus());

				if(null!=current){
					logDO.setUserId(current.getUserId());
					logDO.setUsername(current.getUsername());
				}
				logService.save(logDO);
			}
			return R.ok();
		}catch (Exception e){
			return R.error(1,e.getMessage());
		}

	}


	@RequiresPermissions("system:tMagazine:picture")
	@Log("请求图片上传页面")
	@GetMapping("/uploadPicture/{id}")
	String uploadPicture(@PathVariable("id") Integer id, Model model) {

		TMagazineDO magazineDO = tMagazineService.get(id);
		model.addAttribute("tMagazine", magazineDO);
		return prefix + "/picture";
	}

    @ResponseBody
    @GetMapping("/pictures")
    @RequiresPermissions("system:tMagazine:picture")
    public PageUtils pictures(@RequestParam Map<String, Object> params) {
		if (null!=params && null!=params.get("magazineId")){
			String magazineId = (String) params.get("magazineId");
			if (StringUtils.isBlank(magazineId)){
				params.put("magazineId","0");
			}
		}else {
			params.put("magazineId","0");
		}
        // 查询列表数据
        Query query = new Query(params);
        List<TMagazinePicturesDO> sysFileList = tMagazinePicturesService.list(query);
        int total = tMagazinePicturesService.count(query);
        PageUtils pageUtils = new PageUtils(sysFileList, total);
        return pageUtils;
    }

    @ResponseBody
    @Transactional
    @PostMapping("/pictures/upload")
    @RequiresPermissions("system:tMagazine:picture")
    R upload(@RequestParam("picFile") MultipartFile file,@RequestParam("id") Integer id,
			 @RequestParam("title") String title,@RequestParam("issn") String issn, HttpServletRequest request) {

        String fileName = file.getOriginalFilename();
        String nos = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
        int pageNo = Integer.valueOf(nos);
        fileName = FileUtil.renameToUUID(fileName);
        String url = "/files/" + fileName;
        FileDO sysFile = new FileDO(FileType.fileType(fileName), url, new Date());
        try {
            FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
        } catch (Exception e) {
            return R.error();
        }

        if (sysFileService.save(sysFile) > 0) {
			Map<String, Object> res = new HashMap<>();
        	if (null==id){
				TMagazineDO magazine = new TMagazineDO();
				magazine.setTitle(title);
				magazine.setIssn(issn);
				magazine.setCreatedUser(getUsername());
				tMagazineService.save(magazine);

				TMagazinePicturesDO tMagazinePicturesDO = new TMagazinePicturesDO();
				tMagazinePicturesDO.setMagazineId(magazine.getId());
				tMagazinePicturesDO.setPicture(bootdoConfig.getUploadHost()+url);
				tMagazinePicturesDO.setPageNo(pageNo);
				tMagazinePicturesDO.setCreatedTime(new Date());
				tMagazinePicturesService.save(tMagazinePicturesDO);

				res.put("id",magazine.getId());
				res.put("title",tMagazineService.changeTitlePage(magazine.getId()));
			}else {
				Map<String, Object> map = new HashMap<>(3);
				map.put("magazineId",id);
				map.put("pageNo",pageNo+"");
				List<TMagazinePicturesDO> list = tMagazinePicturesService.list(map);

				if (!CollectionUtils.isEmpty(list)){
					list.forEach(m->{
						TMagazinePicturesDO updateMp = new TMagazinePicturesDO();
						updateMp.setId(m.getId());
						updateMp.setPicture(bootdoConfig.getUploadHost()+url);
						updateMp.setUpdatedTime(new Date());
						tMagazinePicturesService.update(updateMp);
					});
				}else {
					TMagazinePicturesDO tMagazinePicturesDO = new TMagazinePicturesDO();
					tMagazinePicturesDO.setMagazineId(id);
					tMagazinePicturesDO.setPicture(bootdoConfig.getUploadHost()+url);
					tMagazinePicturesDO.setPageNo(pageNo);
					tMagazinePicturesDO.setCreatedTime(new Date());
					tMagazinePicturesService.save(tMagazinePicturesDO);
				}

				res.put("id",id);
				res.put("title",tMagazineService.changeTitlePage(id));
			}
			return R.ok(res);
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/pictures/remove")
    @ResponseBody
	@Transactional
    @RequiresPermissions("system:tMagazine:picture")
    public R picturesRemove(Integer id, Integer type,HttpServletRequest request) {
    	if (null==id || id<=0 || null==type){
    		return R.ok();
		}
    	String picture = null;
    	String title = null;
    	if (0==type){
    		//封面
			TMagazineDO magazineDO = tMagazineService.get(id);
			if (null!=magazineDO){
				picture = magazineDO.getTitlePage();
				//删除内容
				int d = tMagazinePicturesService.removeByMagazine(id,picture);
				//更改封面
				title = tMagazineService.changeTitlePage(id);
			}
		}else if (1==type){
    		//内容
			TMagazinePicturesDO tMagazinePicturesDO = tMagazinePicturesService.get(id);
			if (null!=tMagazinePicturesDO){
				picture = tMagazinePicturesDO.getPicture();
				//删除内容
				tMagazinePicturesService.remove(id);
				//更改封面
				title = tMagazineService.changeTitlePage(tMagazinePicturesDO.getMagazineId());
			}
		} else if (2==type){
    		//清空
			//删除封面
			TMagazineDO updateMp = new TMagazineDO();
			updateMp.setId(id);
			updateMp.setTitlePage("");
			updateMp.setUpdatedTime(new Date());
			tMagazineService.update(updateMp);
			//删除内容
			Map<String, Object> map = new HashMap<>(3);
			map.put("magazineId",id);
			List<TMagazinePicturesDO> listall = tMagazinePicturesService.list(map);
			if (!CollectionUtils.isEmpty(listall)){
				listall.forEach(la->{
					try {
						String fileName = bootdoConfig.getUploadPath() +la.getPicture().substring(la.getPicture().lastIndexOf("/")+1);
						boolean b = FileUtil.deleteFile(fileName);
					} catch (Exception e) {
						e.printStackTrace();
					}
					tMagazinePicturesService.remove(la.getId());
				});
			}
		} else {
			return R.error();
		}

    	if (StringUtils.isNotBlank(picture)){
			String fileName = bootdoConfig.getUploadPath() +picture.substring(picture.lastIndexOf("/")+1);
			boolean b = FileUtil.deleteFile(fileName);
			if (!b) {
				return R.error("数据库记录删除成功，文件删除失败");
			}
		}
    	if (StringUtils.isNotBlank(title)){
			return R.ok().put("title",title);
		}else {
			return R.ok();
		}
    }

	@RequiresPermissions("system:tMagazine:pdf")
	@Log("请求pdf上传页面")
	@GetMapping("/uploadPdf/{id}")
	String uploadPdf(@PathVariable("id") Integer id, Model model) {

		TMagazineDO magazineDO = tMagazineService.get(id);
		model.addAttribute("tMagazine", magazineDO);
		return prefix + "/pdf";
	}


	@ResponseBody
	@Transactional
	@PostMapping("/pdf/upload")
	@RequiresPermissions("system:tMagazine:pdf")
	R uploadpdf(HttpServletRequest request,@RequestParam("pdfFile") MultipartFile file,@RequestParam("id") Integer id,
				 @RequestParam("title") String title,@RequestParam("issn") String issn) {
		String fileName = file.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		String url = "/files/" + fileName;
		FileDO sysFile = new FileDO(FileType.fileType(fileName), url, new Date());
		try {
			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
		} catch (Exception e) {
			return R.error();
		}

		if (sysFileService.save(sysFile) > 0) {
			//保存pdf信息
			String path = bootdoConfig.getUploadPath()+fileName;
			Map<String,Object> map = ItextpdfUtil.getPdfContentAndPages(path);
			TMagazineDO magazine = new TMagazineDO();
			if (null==id){
				magazine.setTitle(title);
				magazine.setIssn(issn);
//				magazine.setContent((String) map.get("content"));
				magazine.setFileContent(bootdoConfig.getUploadHost()+"/files/pdf?filename="+fileName);
				magazine.setFilePages((Integer) map.get("count"));
				magazine.setCreatedUser(getUsername());
				tMagazineService.save(magazine);
			}else {
				magazine.setId(id);
//				magazine.setContent((String) map.get("content"));
				magazine.setFileContent(bootdoConfig.getUploadHost()+"/files/pdf?filename="+fileName);
				magazine.setFilePages((Integer) map.get("count"));
				magazine.setUpdatedTime(new Date());
				magazine.setUpdatedUser(getUsername());
				tMagazineService.update(magazine);
			}
			Map<String, Object> res = new HashMap<>();
			res.put("id",magazine.getId());
			res.put("filecontent",magazine.getFileContent());
			res.put("filepages",magazine.getFilePages());
//			res.put("content",magazine.getContent());
			return R.ok(res);
		}
		return R.error();
	}
}
